// 自定义表单验证工具类
const rules = {
  // 手机号验证
  phone: {
    rule: /^1[3-9]\d{9}$/,
    message: '请输入正确的手机号'
  },
  
  // 邮箱验证
  email: {
    rule: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
    message: '请输入正确的邮箱地址'
  },
  
  // 身份证验证
  idCard: {
    rule: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
    message: '请输入正确的身份证号'
  },
  
  // 密码验证（8-20位，包含字母和数字）
  password: {
    rule: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,20}$/,
    message: '密码必须包含字母和数字，长度8-20位'
  },
  
  // 用户名验证（4-16位字母数字下划线）
  username: {
    rule: /^[a-zA-Z0-9_]{4,16}$/,
    message: '用户名只能包含字母、数字、下划线，长度4-16位'
  }
}

// 验证工具类
class Validator {
  constructor(rules, messages) {
    this.rules = rules
    this.messages = messages
  }

  // 验证单个值
  check(value, ruleString) {
    const ruleList = ruleString.split('|')
    
    for (const rule of ruleList) {
      const [ruleName, param] = rule.split(':')
      
      if (ruleName === 'required' && !this.isNotEmpty(value)) {
        return { valid: false, message: this.messages.required }
      }
      
      if (ruleName === 'min' && this.isNotEmpty(value) && value.length < parseInt(param)) {
        return { valid: false, message: this.messages.min.replace('{min}', param) }
      }
      
      if (ruleName === 'max' && this.isNotEmpty(value) && value.length > parseInt(param)) {
        return { valid: false, message: this.messages.max.replace('{max}', param) }
      }
      
      if (ruleName === 'phone' && this.isNotEmpty(value) && !this.rules.phone.rule.test(value)) {
        return { valid: false, message: this.rules.phone.message }
      }
      
      if (ruleName === 'email' && this.isNotEmpty(value) && !this.rules.email.rule.test(value)) {
        return { valid: false, message: this.rules.email.message }
      }
      
      if (ruleName === 'password' && this.isNotEmpty(value) && !this.rules.password.rule.test(value)) {
        return { valid: false, message: this.rules.password.message }
      }
    }
    
    return { valid: true }
  }

  // 验证表单
  validate(formData, rules) {
    const errors = {}
    
    for (const field in rules) {
      const result = this.check(formData[field], rules[field])
      if (!result.valid) {
        errors[field] = result.message
      }
    }
    
    return {
      valid: Object.keys(errors).length === 0,
      errors
    }
  }

  // 检查是否为空
  isNotEmpty(value) {
    return value !== null && value !== undefined && value !== ''
  }
}

// 创建验证实例
const validator = new Validator(rules, {
  required: '此字段不能为空',
  min: '长度不能少于{min}个字符',
  max: '长度不能超过{max}个字符',
  range: '长度必须在{min}-{max}个字符之间',
  number: '请输入数字',
  integer: '请输入整数',
  decimal: '请输入小数',
  url: '请输入正确的URL地址'
})

export default validator 